package com.sz.app.edi.web.security;

import com.sz.app.edi.service.constants.EdiCommCodes;
import com.sz.biz.app.web.security.AbstractUserRealm;
import com.sz.biz.app.web.security.MyAuthenticationInfo;
import com.sz.common.base.constants.AppDomain;
import com.sz.common.base.dao.DaoSupport;
import com.sz.common.base.utils.CredentialUtils;
import com.sz.common.core.system.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

public class UserRealm extends AbstractUserRealm {


    @Resource(name = "daoSupport")
    private DaoSupport dao;

    /**
     * 验证当前登录的Subject
     * LoginController.login()方法中执行Subject.login()时 执行此方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {

        System.out.println("###【开始认证[SessionId]】" + SecurityUtils.getSubject().getSession().getId());

        SimpleAuthenticationInfo authenticationInfo;
        if (authcToken.getPrincipal().toString().startsWith(EdiCommCodes.MOCK_USER_PREFIX)) {

            String salt = CredentialUtils.generateSalt();
            //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
            authenticationInfo = new MyAuthenticationInfo(
                    AppDomain.EDIDATA,
                    //用户ID
                    -1,
                    //用户名
                    authcToken.getPrincipal().toString(),
                    //密码
                    new Md5Hash(authcToken.getCredentials(), salt).toString().toUpperCase(),
                    //salt=username+salt,采用明文访问时，不需要此句
                    ByteSource.Util.bytes(salt),
                    //realm name
                    getName()
            );


        } else {

            String loginName = (String) authcToken.getPrincipal();
            User user = (User) dao.findForObject("UserMapper.findByLoginValue", loginName);

            if (user == null) {
                //没找到帐号
                throw new UnknownAccountException();
            }
            if (user.getIsLocked()) {
                throw new LockedAccountException();
            }

            //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
            authenticationInfo = new MyAuthenticationInfo(
                    AppDomain.EDIDATA,
                    user.getId(),       //用户ID
                    user.getUserName(), //用户名
                    user.getPassword(), //密码
                    ByteSource.Util.bytes(user.getCredentialSalt()),//salt=username+salt,采用明文访问时，不需要此句
                    getName()  //realm name
            );
        }
        return authenticationInfo;
    }
}

